package dsk.demo.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import dsk.demo.product.vo.CatalogTreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dsk.demo.common.utils.PageUtils;
import dsk.demo.common.utils.Query;

import dsk.demo.product.dao.CatalogDao;
import dsk.demo.product.entity.CatalogEntity;
import dsk.demo.product.service.CatalogService;


@Service("catalogService")
public class CatalogServiceImpl extends ServiceImpl<CatalogDao, CatalogEntity> implements CatalogService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CatalogEntity> page = this.page(
                new Query<CatalogEntity>().getPage(params),
                new QueryWrapper<CatalogEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Cacheable(value = "manager", key = "'catalogTree'", sync = true)
    public CatalogTreeVo queryCatalogTree() {
        QueryWrapper<CatalogEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0);
        List<CatalogEntity> list = this.list(wrapper);
        CatalogTreeVo catalogTreeVo = new CatalogTreeVo();
        catalogTreeVo.setId(0);
        CatalogTreeVo catalogTreeVo1 = collectNodes(list, catalogTreeVo);
        return catalogTreeVo1;
    }

    /**
     * 查询全部子节点, name 不可传值
     * @param name
     * @return
     */
    @Override
    @Cacheable(value = "manager", key = "'catalogNodes'+#name", sync = true)
    public List<CatalogEntity> selectAllChildNode(String name) {
        List<CatalogEntity> entities = this.baseMapper.selectAllChildNode("");
        return entities;
    }

    /**
     * 找到当前 实体类下的所有的子节点
     * @param list
     * @param node
     */
    private CatalogTreeVo collectNodes(List<CatalogEntity> list,CatalogTreeVo node){
        //查父节点id等于node的 所有节点
        List<CatalogTreeVo> collect = list.stream().filter(item -> {
            return item.getParentId() == node.getId();
        }).map(item->{
            CatalogTreeVo catalogTreeVo = new CatalogTreeVo();
            BeanUtils.copyProperties(item,catalogTreeVo);
            return catalogTreeVo;
        }).collect(Collectors.toList());

        //对于子节点集合，再去收集它的每个子节点的子节点
        List<CatalogTreeVo> collect1 = collect.stream().map(item -> {
            CatalogTreeVo catalogTreeVo = collectNodes(list, item);
            return catalogTreeVo;
        }).collect(Collectors.toList());

        node.setChildren(collect1);
        return node;
    }

}